import os
import signal
import time
import re
import serial
import serial.tools.list_ports

from logger.logger import Log


#    串口模块

# 获取串口列表 转换为列表并返回
def load_port_list():
    if serial.tools.list_ports.comports() != []:
        print("检测到串口:", end=' ')
        print(serial.tools.list_ports.comports())
    else:
        Log.logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!未检测到串口!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        Log.logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!程序即将退出!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        pid = os.getpid()  # 获取当前进程的PID
        os.kill(pid, signal.SIGTERM)  # 主动结束指定ID的程序运行
    return list(serial.tools.list_ports.comports())


class SerialPort:
    def close(self):
        self.p.close()
        # self.p = None

    # # 尝试从串口中读取数据，在等待一段时间后检查是否有可读取的数据，并根据情况读取不同长度的数据进行返回
    def read(self, delay):
        time.sleep(delay / 1000)
        num = self.p.inWaiting()
        if num > 0:
            return self.p.read(num)
        return self.p.read()

    # def read(self, delay):
    #     time.sleep(delay / 1000)
    #     data = b''  # 用于存储读取到的数据
    #     start_time = time.time()  # 记录开始时间
    #
    #     while True:
    #         num = self.p.inWaiting()  # 获取缓冲区中待读取的字节数
    #         if num > 0:
    #             data += self.p.read(num)  # 将数据添加到已读取的数据中
    #         else:
    #             if time.time() - start_time >= (delay / 1000):
    #                 break  # 如果超过延迟时间，退出循环
    #
    #     return data

    # 根据输入的数据类型(输入是否包含 HEX )，进行不同的处理方式，最终将处理后的数据写入到串口中
    def write(self, data: str):
        if 'Hex:' in data:
            data = re.findall(r'(?<=Hex:).+', data)[0]
            buf = []
            for h in data.split(" "):
                buf += bytes.fromhex(h)
            self.p.write(buf)
        else:
            buf = data.encode('utf-8')
            self.p.write(buf)

    def is_open(self) -> bool:
        return self.p.isOpen()

    def open(self):
        # 创建了一个串行通信对象
        self.p = serial.Serial(self.port, self.bitrate, timeout=0.5)
        # 获取当前可读取的字节数，即查询串口缓冲区中等待读取的字节数。这个方法返回一个整数，表示当前可用于读取的字节数
        # self.p.Inwaiting()

    def __init__(self, port: str, bitrate: int):
        self.p = None
        self.port = port
        self.bitrate = bitrate


if __name__ == '__main__':
    # p=load_port_list()
    # print('port list ',p[0].device)
    s = SerialPort("COM3", 115200)
    try:
        s.open()
        if s.is_open():
            print("Open Serial /dev/ttyUSB0 Successful")
        s.write('\n')
        readback = s.read(1000).decode('utf-8')
        print(readback)
        if "OpenWrt login:" in readback:
            s.write('root\n')
            readback = s.read(1000).decode('utf-8')
            print(readback)
            if "Passsword:" in readback:
                s.write('admin\n')
                readback = s.read(1000).decode('utf-8')
                print(readback)
        elif 'root@OpenWrt:~#' in readback:
            s.write('cd /home \n')
            s.write('pwd\n')
            readback = s.read(1000).decode('utf-8')
            print(readback)
        else:
            s.write('\n')
            readback = s.read(1000).decode('utf-8')
    except Exception as e:
        print('串口打开失败', e)
        s.close()
